import Vue from "vue";
import Router from "vue-router";
import MenuView from "@/views/common/MenuView";
import PageView from "@/views/common/PageView";
import LoginView from "@/views/login/Common";
import EmptyPageView from "@/views/common/EmptyPageView";
import HomePageView from "@/views/HomePage";
import db from "utils/localstorage";
import { api } from "@/api";

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};
Vue.use(Router);

let constRouter = [
  {
    path: "/login",
    name: "登录页",
    component: LoginView
  },
  {
    path: "/",
    name: "首页",
    redirect: "/personal"
  },
  {
    path: "/",
    name: "静态路由",
    component: MenuView,
    children: [
      {
        path: "/",
        name: "静态路由",
        component: PageView,
        children: [
          {
            name: "学籍异动修改页",
            path: "/student/change/save",
            component: () => import("@/views/student/change/save/save")
          },
          {
            name: "学籍异动查看页",
            path: "/student/change/view",
            component: () => import("@/views/student/change/view")
          },
          {
            name: "学生导师异动",
            path: "/student/change/tutorChange",
            component: () =>
              import("@/views/student/change/tutorChange/tutorChange")
          },
          {
            name: "学籍信息修改页",
            path: "/student/stuStatus/stuStatusEdit",
            component: () =>
              import("@/views/student/info/checkedList/studentEdit")
          },
          {
            name: "学籍信息详情",
            path: "/student/stuStatus/search/stuView",
            component: () => import("@/views/student/stuStatus/search/stuView")
          },
          {
            name: "导师详细信息",
            path: "/teacher/info/:dsbh",
            component: () => import("@/views/teacher/teacherView")
          },
          {
            name: "导师招生信息修改",
            path: "/teacher/info/:dsbh/recruit",
            component: () =>
              import("@/views/teacher/manage/infoList/recruitModify")
          },
          {
            name: "导师信息审核页",
            path: "/teacher/info/:dsbh/check",
            component: () => import("@/views/teacher/manage/check/checkInfo")
          },
          {
            name: "导师信息补充页",
            path: "/teacher/info/:dsbh/supplement",
            component: () =>
              import("@/views/teacher/manage/supplement/supplement")
          },
          {
            name: "导师信息修改",
            path: "/teacher/info/:dsbh/edit",
            component: () => import("@/views/teacher/manage/infoList/infoEdit")
          },
          {
            name: "基地导师信息修改",
            path: "/degree/trainingBase/teacher/:id/edit",
            component: () =>
              import("@/views/degree/trainingBase/component/teacherInfoEdit")
          },
          {
            name: "基地信息修改",
            path: "/degree/trainingBase/base/:id/edit",
            component: () =>
              import("@/views/degree/trainingBase/component/baseInfoEdit")
          },
          {
            name: "新增课程信息",
            path: "/cultivate/course/add",
            component: () => import("@/views/cultivate/course/courseAdd")
          },
          {
            name: "课程信息审核",
            path: "/cultivate/course/info/:id/check",
            component: () => import("@/views/cultivate/course/courseCheck")
          },
          {
            name: "教师信息",
            path: "/cultivate/teacher/info/:bh",
            component: () => import("@/views/cultivate/teacher/teacherDetail")
          },
          {
            name: "教师信息审核",
            path: "/cultivate/teacher/info/:bh/check",
            component: () => import("@/views/cultivate/teacher/teacherCheck")
          },
          {
            name: "添加教师",
            path: "/cultivate/teacher/add",
            component: () => import("@/views/cultivate/teacher/teacherEdit")
          },
          {
            name: "添加培养方案模板",
            path: "/cultivate/template/add",
            component: () => import("@/views/cultivate/template/add/add")
          },
          {
            name: "培养方案详情模板",
            path: "/cultivate/template/detail/:id",
            component: () => import("@/views/cultivate/template/detail")
          },
          {
            name: "培养方案详情",
            path: "/cultivate/scheme/detail/:id",
            component: () => import("@/views/cultivate/scheme/detail")
          },
          {
            name: "培养计划修改",
            path: "/cultivate/plan/detail/:id/edit",
            component: () => import("@/views/cultivate/plan/planEdit")
          },
          {
            name: "添加排课",
            path: "/cultivate/arrangeCourse/add",
            component: () => import("@/views/cultivate/arrangeCourse/add")
          },
          {
            name: "添加考試安排",
            path: "/cultivate/exam/add",
            component: () => import("@/views/cultivate/exam/add")
          },
          {
            path: "/exception/401",
            name: "Exception401",
            component: () =>
              import(/* webpackChunkName: "fail" */ "@/views/error/401"),
            meta: { title: "401" }
          },
          {
            name: "学士学位分数线设置",
            path: "/doctorRecruit/fractional/professionalStu",
            component: () =>
              import(
                "@/views/doctorRecruit/fractional/professionalStu/professionalStu"
              )
          },
          {
            name: "学士学位分数线设置",
            path: "/doctorRecruit/fractional/codeStu",
            component: () =>
              import("@/views/doctorRecruit/fractional/codeStu/codeStu")
          },
          {
            name: "专业实践申请审核",
            path: "/degree/profession/practiceApply/detail",
            component: () =>
              import("@/views/degree/profession/practiceApply/detail")
          },
          {
            name: "专业实践申请修改",
            path: "/degree/profession/practiceApply/modify",
            component: () =>
              import("@/views/degree/profession/practiceApply/modify")
          },
          {
            name: "专业实践结果评价审核",
            path: "/degree/profession/practiceResult/detail",
            component: () =>
              import("@/views/degree/profession/practiceResult/detail")
          },
          {
            name: "专业实践结果评价修改",
            path: "/degree/profession/practiceResult/modify",
            component: () =>
              import("@/views/degree/profession/practiceResult/modify")
          },
          {
            name: "调课",
            path: "/cultivate/arrangeCourse/tk",
            component: () => import("@/views/cultivate/arrangeCourse/tk")
          },
          {
            name: "绑定设置",
            path: "/bind",
            hidden: true,
            component: () => import("@/views/personal/bindSetting")
          },
          {
            name: "公告详情",
            path: "/bind/noticeView",
            component: () => import("@/views/personal/noticeView")
          },
          {
            name: "海外导师招生信息修改",
            path: "/overseas/info/:dsbh/recruit",
            component: () =>
              import("@/views/overseas/manage/infoList/recruitModify")
          },
          {
            name: "海外导师信息审核页",
            path: "/overseas/info/:dsbh/check",
            component: () => import("@/views/overseas/manage/check/checkInfo")
          },
          {
            name: "海外学籍信息详情",
            path: "/overseas/stuStatus/search/stuView",
            component: () => import("@/views/overseas/stuStatus/search/stuView")
          },
          {
            name: "海外学籍信息修改页",
            path: "/overseas/stuStatus/stuStatusEdit",
            component: () =>
              import("@/views/overseas/info/checkedList/studentEdit")
          },
          {
            name: "海外项目信息修改",
            path: "/overseas/project/info/:dsbh/edit",
            component: () =>
              import("@/views/overseas/project/infoList/infoEdit")
          },
          {
            name: "海外项目信息审核页",
            path: "/overseas/project/info/:dsbh/check",
            component: () => import("@/views/overseas/project/check/checkInfo")
          },
          {
            name: "海外导师信息修改",
            path: "/overseas/teacher/info/:dsbh/edit",
            component: () => import("@/views/overseas/manage/infoList/infoEdit")
          },
          {
            name: "海外学籍信息修改页",
            path: "/overseas/stuStatus/stuStatusEdit",
            component: () =>
              import("@/views/overseas/info/checkedList/studentEdit")
          },
          {
            name: "导师详细信息",
            path: "/overseas/teacher/info/:dsbh",
            component: () => import("@/views/overseas/manage/teacherView")
          }
        ]
      }
    ]
  }
];

let router = new Router({
  routes: constRouter
});

const whiteList = ["/login"];

let asyncRouter;

// 导航守卫，渲染动态路由
router.beforeEach((to, from, next) => {
  if (whiteList.indexOf(to.path) !== -1) {
    next();
  }
  let token = db.get("USER_TOKEN");
  let user = db.get("USER");
  let userRouter = get("USER_ROUTER");
  if (token.length && user) {
    if (!asyncRouter) {
      if (!userRouter) {
        api.menu.findByUserId(user.id).then(res => {
          asyncRouter = res.data;
          save("USER_ROUTER", asyncRouter);
          go(to, next);
        });
      } else {
        asyncRouter = userRouter;
        go(to, next);
      }
    } else {
      next();
    }
  } else {
    next("/login");
  }
});

function go(to, next) {
  asyncRouter = filterAsyncRouter(asyncRouter);
  console.log("abc", asyncRouter);
  asyncRouter[0].children.push({ path: "*", redirect: "/exception/401" });
  router.addRoutes(asyncRouter);
  console.log("abc", router);
  next({ ...to, replace: true });
}

function save(name, data) {
  localStorage.setItem(name, JSON.stringify(data));
}

function get(name) {
  return JSON.parse(localStorage.getItem(name));
}

function filterAsyncRouter(routes) {
  console.log(routes);
  return routes.filter(route => {
    let component = route.component;
    if (component) {
      switch (route.component) {
        case "MenuView":
          route.component = MenuView;
          break;
        case "PageView":
          route.component = PageView;
          break;
        case "EmptyPageView":
          route.component = EmptyPageView;
          break;
        case "HomePageView":
          route.component = HomePageView;
          break;
        default:
          route.component = view(component);
      }
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children);
      }
      return true;
    }
  });
}

function view(path) {
  // return require(`@/views/${path}.vue`).default
  return resolve => require([`@/views/${path}.vue`], resolve);
}
export default router;
